<style lang="less">
@import "../../styles/common.less";
.ivu-table-sort {
  margin-top: 13px;
}
</style>

<template>
  <div>
    <Row class="margin-top-10">
      <Col span="24">
        <Card>
          <p slot="title">出库记录</p>
          <Row>
            <RadioGroup v-model="dateSearchType">
              <Radio label="0">全部</Radio>
              <Radio label="1">今日</Radio>
              <Radio label="2">昨日</Radio>
              <Radio label="3">最近七日</Radio>
              <Radio label="4" disabled>自定义</Radio>
              <DatePicker
                v-model="searchDateRange"
                @click.native="dateChange"
                type="daterange"
                placement="bottom-end"
                placeholder="选择日期"
                style="width: 200px"
              ></DatePicker>
              <Input v-model="outboundProductName" placeholder="商品名称" style="width: 150px" />
              <Select
                clearable
                v-model="searchTranType"
                placeholder="出库类型"
                style="width: 120px"
              >
                <Option :value="item" :key="item" v-for="item in outboundTypeList">{{item}}</Option>
              </Select>
              <Button type="success" @click="getData()">查询</Button>
            </RadioGroup>
            <div class="f_r">
              <Button type="primary" @click="add()">商品出库</Button>
              <Button :loading="exportLoading" type="warning" @click="searchInventoryOutbound(true)">导出</Button>
            </div>
          </Row>
          <Row class="margin-top-10">
            <Col span="24">
              <div>
                <Table
                  class="table"
                  :columns="outboundColumn"
                  :data="outboundData"
                  border
                  stripe
                  ref="outboundTable"
                  :loading="loading"
                ></Table>
              </div>
            </Col>
          </Row>
          <Row class="margin-top-10">
            <Col span="18">
              <Page
                ref="outboundPage"
                :total="total"
                size="small"
                :pageSize="pageSize"
                @on-change="changePage"
                show-total
                show-elevator
              ></Page>
            </Col>
          </Row>
        </Card>
      </Col>
    </Row>
    <Modal :closable="false" :mask-closable="false" v-model="addModel" width="800" title="商品出库">
      <Form ref="addOutboundForm" :model="addValue" :label-width="80">
        <Row>
          <Col span="12">
            <FormItem label="出库类型" class="ivu-form-item-required">
              <Select v-model="addValue.tranType" style="width:200px">
                <Option :value="item" :key="item" v-for="item in outboundTypeList">{{item}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="出库时间" class="ivu-form-item-required">
              <DatePicker
                v-model="addValue.tranTime"
                type="datetime"
                placeholder="选择出库时间"
                style="width:200px"
              ></DatePicker>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="6">
            <FormItem>
              <Button icon="plus-round" type="ghost" @click="showProductModal">选择商品</Button>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="22">
            <FormItem>
              <Table height="300" :columns="outboundProductColumn" :data="outboundProductData" border stripe></Table>
            </FormItem>
          </Col>
        </Row>
        <Row class="margin-top-10">
          <Col span="24">
            <FormItem label="备注">
              <Input
                v-model="addValue.memo"
                :rows="5"
                type="textarea"
                placeholder="请输出备注"
                :maxlength="500"
                style="width:90%"
              ></Input>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="text" @click="addModel=false">取消</Button>
        <Button type="primary" :loading="addLoading" @click="addOk">确定</Button>
      </div>
    </Modal>
    <Modal :closable="false" :mask-closable="false" width="1000" title="选择商品" v-model="showSelectProduct">
      <Row>
        <div>
          <Input
            v-model="searchProductName"
            placeholder="商品名称"
            type="text"
            style="width: 200px"
            clearable
          />
          <Button type="success" @click="handleProductSearch">查询</Button>
        </div>
      </Row>
      <Row class="margin-top-10">
        <Col span="24">
          <div>
            <Table
              @on-selection-change="selectProduct"
              :loading="loading"
              :columns="productColumn"
              :data="productData"
              border
              stripe
            ></Table>
          </div>
        </Col>
      </Row>
      <Row class="margin-top-10">
        <Page
          ref="productPage"
          :total="productTotal"
          size="small"
          :pageSize="8"
          @on-change="changeProductPage"
          show-total
          show-elevator
        ></Page>
      </Row>
      <div slot="footer">
        <Button type="default" @click="showSelectProduct = false">关闭</Button>
        <Button type="primary" @click="addOutboundProduct">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      dateSearchType: "0",
      outboundProductName:'',
      loading: false,
      exportLoading: false,
      addLoading: false,
      addValue: {},
      searchDateRange: [],
      searchTranType:'',
      showSelectProduct: false,
      outboundTypeList: ["领用出库", "销售出库", "调拨出库", "其他出库"],
      outboundColumn: [
        {
          title: "出库时间",
          align: "center",
          key: "tranTime",
          width: 150
        },
        {
          title: "商家",
          align: "center",
          width: 250,
          key: "merchantName"
        },
        {
          title: "商品",
          align: "center",
          key: "productName"
        },
        {
          title: "规格",
          align: "center",
          key: "skuName",
          width: 200
        },
        {
          title: "出库类型",
          align: "center",
          key: "tranType",
          width: 150
        },
        {
          title: "出库数量",
          align: "center",
          key: "tranUnit",
          width: 150
        },
        {
          title: "备注",
          align: "center",
          key: "memo",
          width: 150
        }
      ],
      outboundData: [],
      outboundProductColumn: [
        {
          title: "商品名称",
          align: "center",
          render: (h, params) => {
            return h(
              "span",
              {
                props: {
                  row: params.row
                }
              },
              params.row.productDTO.productName
            );
          }
        },
        {
          title: "规格",
          align: "center",
          width: 200,
          render: (h, params) => {
            let skuName = '';
            if(params.row.productDTO.skuEnabled){
              skuName = params.row.productSkuDTO.skuName
            }
            return h(
              "span",
              {
                props: {
                  row: params.row
                }
              },
              skuName
            );
          }
        },
        {
          title: "出库数量",
          align: "center",
          key: "tranUnit",
          width: 100,
          render: (h, params) => {
            return h("InputNumber", {
              props: {
                class: "ivu-input-number-input",
                min: 1,
                value: params.row.tranUnit
              },
              on: {
                'on-change': val => {
                  this.outboundProductData[params.index].tranUnit = val;
                }
              }
            });
          }
        },
        {
          title: "操作",
          align: "center",
          width: 120,
          render: (h, params) => {
            return h("span", {}, [
              h(
                "Button",
                {
                  props: {
                    type: "ghost",
                    row: params.row,
                    size: "small"
                  },
                  style: {
                    marginRight: "8px"
                  },
                  on: {
                    click: () => {
                      this.delOutboundProduct(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      outboundProductData:[],
      searchProductName:'',
      productColumn: [
        {
          type: "selection",
          align: "center",
          width: 60
        },
        {
          title: "商家",
          align: "center",
          width: 200,
          render: (h, params) => {
            return h(
              "span",
              {
                props: {
                  row: params.row
                }
              },
              params.row.merchantDTO.merchantName
            );
          }
        },
        {
          title: "商品图片",
          align: "center",
          width: 150,
          render: (h, params) => {
            return h("img", {
              attrs: {
                src: params.row.productMainImage.url
              },
              style: {
                width: "60px",
                height: "48px",
                display: "inline-block",
                margin: "5px 0"
              }
            });
          }
        },
        {
          title: "商品名称",
          align: "center",
          render: (h, params) => {
            return h(
              "span",
              {
                props: {
                  row: params.row
                }
              },
              params.row.productName
            );
          }
        },
        {
          title: "库存",
          align: "center",
          width: 120,
          key: "totalUnit"
        }
      ],
      productData:[],
      total: 0,
      productTotal: 0,
      pageSize: 20,
      startIndex: 0,
      addModel: false
    };
  },
  methods: {
    //日期查询条件改变
    dateChange() {
      this.dateSearchType = "4";
    },
    showProductModal(){
      this.showSelectProduct = true;
      this.handleProductSearch();
    },
    handleProductSearch() {
      this.resetProductPage();
      this.searchProduct();
    },
    resetProductPage(){
      this.productPageNo = 1;
      this.productTotal = 0;
      this.productData = [];
      //重新设置成显示第一页
      this.$nextTick(function() {
        this.$refs["productPage"].currentPage = 1;
      });
    },
    changeProductPage(productPageNo) {
      this.productPageNo = productPageNo;
      this.searchProduct();
    },
    searchProduct() {
      let keyArray = [];
      var searchOptions = {
        startIndex: (this.productPageNo-1)*8,
        pageSize: 8
      };
      //判断是否有商品名称查询条件
      if (this.searchProductName) {
        keyArray.push("PRODUCT_NAME");
        searchOptions.productName = this.searchProductName;
      }
      searchOptions.keyArray = keyArray;
      this.loading = true;
      this.$http
        .post("/admin/searchInventoryProduct", this.common.request(searchOptions))
        .then(
          response => {
            if (response.data.body.status.statusCode == 0) {
              this.loading = false;
              this.productData = response.data.body.data.products;
              this.productTotal = response.data.body.data.total;
            } else {
              this.loading = false;
              this.$Message.error(response.data.body.status.errorDesc);
            }
          },
          response => {
            this.$Message.error("失败，请稍后重试");
          }
        );
    },
    //商品多选框选中事件
    selectProduct(selection) {
      this.selectedProduct = selection;
    },
    addOutboundProduct(){
      let that = this;
      that.selectedProduct.forEach(function(val,index){
        //多规格
        if(val.skuEnabled){
          let skuList = val.skuList;
          skuList.forEach(function(sku,skuIndex){
              let skuAttrValueList = sku.skuAttrValueList;
              let skuName = '';
              skuAttrValueList.forEach(function(skuAttrValue,attrIndex){
                skuName = skuName + skuAttrValue.skuAttrValue + ' ';
              })
              var outboundProduct = {
              productDTO: val,
              productSkuDTO: {
                productSkuUuid: sku.productSkuUuid,
                skuName: skuName,
                skuTotalUnit: sku.skuTotalUnit
              },
              tranUnit: 10
            }
            that.outboundProductData.push(outboundProduct);
          })
        }
        //单规格
        else{
          var outboundProduct = {
            productDTO: val,
            tranUnit: 10
          }
          that.outboundProductData.push(outboundProduct);
        }
        
      });
      this.showSelectProduct = false;
    },
    delOutboundProduct(index){
        this.outboundProductData.splice(index,1);
    },
    searchInventoryOutbound(isExport) {
      let that = this;
      let searchOptions = {
        startIndex: this.startIndex,
        pageSize: this.pageSize
      };
      let keyArray = [];
      //判断是否有出库类型查询条件
      if (this.searchTranType) {
        keyArray.push("TRAN_TYPE");
        searchOptions.tranType = this.searchTranType;
      }
      //判断是否有商品名称查询条件
      if (this.outboundProductName) {
        keyArray.push("PRODUCT_NAME");
        searchOptions.productName = this.outboundProductName;
      }
      //选择日期
      if (this.dateSearchType) {
        let dateType = this.dateSearchType;
        let startDate = null;
        let endDate = null;
        let currentDate = new Date();
         if (dateType == "1") {
          startDate = currentDate;
          endDate = currentDate;
        } else if (dateType == "2") {
          currentDate.setDate(currentDate.getDate() - 1);
          startDate = currentDate;
          endDate = currentDate;
        } else if (dateType == "3") {
          let tDate = new Date();
          tDate.setDate(currentDate.getDate() - 7);
          startDate = tDate;
          endDate = currentDate;
        } else if (dateType == "4") {
          let t = this.searchDateRange;
          let startDateT = t[0];
          let endDateT = t[1];
          startDate = startDateT;
          endDate = endDateT;
        }
        if (dateType != "0") {
            keyArray.push("TRAN_TIME");
            searchOptions.tranTimeStart = startDate;
            searchOptions.tranTimeEnd = endDate;
        }
      }
      searchOptions.keyArray = keyArray;
      if(isExport){
        this.exportLoading = true;
        searchOptions.startIndex = 0;
        searchOptions.pageSize = 9999;
      }
      else
        this.loading = true;
      this.$http
        .post(
          "/admin/searchInventoryOutbound",
          this.common.request(searchOptions)
        )
        .then(
          response => {
            if(isExport){
                this.exportLoading = false;
            }
            else
                this.loading = false;
            if (response.data.body.status.statusCode == 0) {
              var data = response.data.body.data;
              if(isExport){
                var exportData = [
                    "商品出库记录",
                    that.outboundColumn,
                    data.outboundList
                ];
                that.$refs.outboundTable.exportCsv({
                    filename: exportData[0],
                    columns: exportData[1],
                    data: exportData[2]
                });
              }else{
                this.outboundData = data.outboundList;
                this.total = data.total;
              }
            } else {
              this.$Message.error(response.data.body.status.errorDesc);
            }
          },
          response => {
            this.loading = false;
            this.$Message.error(response.data.body.status.errorDesc);
          }
        );
    },
    getData() {
      this.searchInventoryOutbound();
    },
    //处理分页-页数改变
    changePage(index) {
      this.startIndex = (index - 1) * this.pageSize;
      this.searchInventoryOutbound();
    },
    add() {
      this.addModel = true;
    },
    addOk() {
        let that = this;
        if(!this.addValue.tranType){
            this.$Message.error("未选择出库类型");
            return;
        }
        if(!this.addValue.tranTime){
            this.$Message.error("未填写出库时间");
            return;
        }
        if(this.outboundProductData.length==0){
            this.$Message.error("未选择出库商品");
            return;
        }
        let outboundList = [];
        this.outboundProductData.forEach(function(val,index){
            let item = {
                tranType: that.addValue.tranType,
                tranTime: that.addValue.tranTime.format('yyyy-MM-dd hh:mm:ss'),
                tranUnit: val.tranUnit,
                memo: that.addValue.memo,
                productDTO:{
                    productUuid: val.productDTO.productUuid
                }
            }
            if(val.productSkuDTO){
              item.productSkuDTO = {
                productSkuUuid: val.productSkuDTO.productSkuUuid
              }
              item.skuName = val.productSkuDTO.skuName
            }
            outboundList.push(item)
        })
        this.addLoading = true;
          this.$http
            .post("/admin/createInventoryOutbound", this.common.request({
                outboundList: outboundList
            }))
            .then(
              response => {
                this.addLoading = false;
                if (response.data.body.status.statusCode == 0) {
                  var data = response.data.body.data;
                  this.$Notice.success({
                    title: "商品出库成功",
                    duration: 2
                  });
                  this.addModel = false;
                  this.searchInventoryOutbound();
                } else {
                  this.$Notice.error({
                    title: "失败",
                    desc: response.data.body.status.errorDesc,
                    duration: 2
                  });
                }
              },
              response => {
                this.addLoading = false;
                this.$Message.error("出错了，请稍后重试");
              }
            );
    }
  },
  created() {
    this.getData();
  }
};
</script>
